# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import Context, RequestContext
from sprt import createExtInfo
from sprt.admin.models import Dept, get_my_depts, get_my_branchs2
from sprt.approved.forms import ApproveForm
from sprt.approved.models import Unapprove, Approve
from sprt.schedule.models import Schedule


@login_required
def index(request):
    c = RequestContext(request)
    createExtInfo(request, c)
    return render_to_response("approved/index.html",c) 

@login_required
def list_unapprove(request):
    if not request.META["management_role"]:
        raise Http404
    pn = request.GET.get('pageNum')
    c = RequestContext(request)
    query_set = Unapprove.objects.raw("select S.id as schedule_id,T.name as schedule_type_name,S.title as schedule_title, S.keyword as schedule_keyword, S.start_date as schedule_start_date, S.end_date as schedule_end_date, S.created_by_id as schedule_created_by, U2.username as schedule_created_by_info, A.id as approve_id, A.status from SCHEDULE S inner join SCHEDULE_TYPE T on S.schedule_type_id = T.id inner join USER_DETAIL U on S.created_by_id = U.user_id inner join auth_user U2 on U.user_id = U2.id inner join DEPT D on U.dept_id = D.id left join APPROVE a on S.id = A.schedule_id where D.principal_auth_user_id = %d and S.status = 1 and (A.status =0 or A.status is null)" % request.user.id)
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))
#    from django.db import connection
#    cursor = connection.cursor()
#    cursor.execute("select count(*) from SCHEDULE S inner join SCHEDULE_TYPE T on S.schedule_type_id = T.id inner join USER_DETAIL U on S.created_by_id = U.user_id inner join auth_user U2 on U.user_id = U2.id inner join DEPT D on U.dept_id = D.id left join APPROVE a on S.id = A.schedule_id where D.principal_auth_user_id = %d and S.status = 1 and (A.status =0 or A.status is null)" % request.user.id)
#    paginator._count = cursor.fetchone()[0]
#    cursor.close()
    if pn == None or len(pn) == 0:
        pn =1
    else:
        pn = int(pn)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
        
    c["list"] = data_list
    c["nav_url"]="%s?pageNum=%s" % (request.path,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    createExtInfo(request,c)
    return render_to_response("approved/unapprove.html",c)

@login_required
def my(request,dept_id):
    c = RequestContext(request)
    if not request.META["management_role"]:
        raise Http404
    pn = int(request.GET.get('pageNum',1))
    
    query_set = Unapprove.objects.raw("select S.id as schedule_id,T.name as schedule_type_name,S.title as schedule_title, S.keyword as schedule_keyword, S.start_date as schedule_start_date, S.end_date as schedule_end_date, S.created_by_id as schedule_created_by, U2.username as schedule_created_by_info, A.id as approve_id, A.status from SCHEDULE S inner join SCHEDULE_TYPE T on S.schedule_type_id = T.id inner join USER_DETAIL U on S.created_by_id = U.user_id inner join auth_user U2 on U.user_id = U2.id left join APPROVE a on S.id = A.schedule_id where U.dept_id = %d and (S.status = 1 or S.status =2) " % (int(dept_id)))
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c["list"] = data_list
    c["nav_url"]="%s?pageNum=%s" % (request.path,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    createExtInfo(request,c)
    return render_to_response("approved/unapprove.html",c)

@login_required
def branch(request,dept_id):
    c = RequestContext(request)
    if not request.META["management_role"]:
        raise Http404
    
    pn = int(request.GET.get('pageNum',1))
    
    query_set = Approve.objects.raw("select A.* from APPROVE A inner join SCHEDULE S on A.schedule_id = S.id inner join USER_DETAIL U on S.created_by_id = U.user_id inner join DEPT D on U.dept_id = D.id where A.status = 1 and U.dept_id = %d" % int(dept_id))
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c["list"] = data_list
    c["nav_url"]="%s?pageNum=%s" % (request.path,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    createExtInfo(request,c)
    return render_to_response("approved/list.html",c)

@login_required
def view_by_user(request, uid):
    if not request.META["management_role"]:
        raise Http404
    from sprt.accounts.models import UserDetail
    try:
        user = UserDetail.objects.get(pk=uid)
    except UserDetail.DoesNotExist:
        raise Http404
    my_dept_qs = get_my_depts(request.user)
    is_my_dept = my_dept_qs != None and user.dept in my_dept_qs
    if not is_my_dept:
        my_branchs = get_my_branchs2(request.user)
        if not user.dept in my_branchs:
            raise Http404

    pn = int(request.GET.get('pageNum',1))

    c = RequestContext(request)
    if is_my_dept:
        
        query_set = Unapprove.objects.raw("select S.id as schedule_id,T.name as schedule_type_name, S.title as schedule_title, S.keyword as schedule_keyword, S.start_date as schedule_start_date, S.end_date as schedule_end_date, S.created_by_id as schedule_created_by, U2.username as schedule_created_by_info, A.id as approve_id, A.status from SCHEDULE S inner join SCHEDULE_TYPE T on S.schedule_type_id = T.id inner join USER_DETAIL U on S.created_by_id = U.user_id inner join auth_user U2 on U.user_id = U2.id left join APPROVE a on S.id = A.schedule_id where S.created_by_id = %d and (S.status = 1 or S.status = 2)" % int(uid)) #schedul.status = 1, commit, 2 approved
        paginator = Paginator(query_set,20)
        paginator._count = len(list(query_set))
        template="approved/unapprove.html"
    else:
        query_set = Approve.objects.raw("select A.* from APPROVE A inner join SCHEDULE S on A.schedule_id = S.id inner join USER_DETAIL U on S.created_by_id = U.user_id where A.status = 1 and S.created_by_id = %d" % int(uid))
        paginator = Paginator(query_set,20)
        paginator._count = len(list(query_set))
        template = "approved/list.html"
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c["list"] = data_list
    c["nav_url"]="%s?pageNum=%s" % (request.path,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    createExtInfo(request,c)
    return render_to_response(template,c)
        

@login_required
def list_done(request):
    if not request.META["management_role"]:
        raise Http404
    
    pn = int(request.GET.get('pageNum',1))
    c = RequestContext(request)
    
    paginator = Paginator(Approve.objects.filter(created_by=request.user),20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c["list"] = data_list
    c["nav_url"]="%s?pageNum=%s" % (request.path,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    createExtInfo(request,c)
    return render_to_response("approved/done.html",c)

@login_required
def list_approved(request):
    pn = int(request.GET.get('pageNum',1))
    c = RequestContext(request)

    query_set = Approve.objects.raw("select A.* from APPROVE A inner join SCHEDULE S on A.schedule_id = S.id where A.status = 1 and S.created_by_id = %d" % request.user.id)
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))    
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c["list"] = data_list
    c["nav_url"]="%s?pageNum=%s" % (request.path,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    createExtInfo(request,c)
    return render_to_response("approved/list.html",c)

@login_required
def view(request, id):
    try:
        approved=Approve.objects.get(pk=id)
    except Approve.DoesNotExist:
        raise Http404
    c = RequestContext(request)
    c["approved"]=approved
    
    if request.META["management_role"]:
        depts = get_my_depts(request.user)
        if depts==None or len(depts) == 0:
            raise Http404
    
    createExtInfo(request,c)
    return render_to_response("approved/view.html",c)

@login_required
def do(request,schedule_id):
    try:
        schedule = Schedule.objects.get(pk=schedule_id)
    except Schedule.DoesNotExist:
        raise Http404
    if request.method == 'POST':
        form = ApproveForm(request.POST)
        if form.is_valid():
            if "/approved/commit" in request.path:
                form.commit_approve(_schedule=schedule, created_by=request.user)
                return HttpResponseRedirect("/approved/done")
            else:
                form.save_form(_schedule=schedule,created_by=request.user)
                return HttpResponseRedirect("/approved/unapprove")
        else:
            print "form.invalid()"
    else:
        form = ApproveForm()
    c = RequestContext(request)
    c.update(csrf(request))
    c["form"]=form
    createExtInfo(request, c)
    return render_to_response("approved/do.html",c)

@login_required
def do2(request, schedule_id, id):
    try:
        schedule = Schedule.objects.get(pk=schedule_id)
        approve = Approve.objects.get(pk=id)
    except Schedule.DoesNotExist, Approve.DoesNotExist:
        raise Http404
    if request.method == 'POST':
        form = ApproveForm(request.POST,instance=approve)
        if form.is_valid():
            if "/approved/commit" in request.path:
                form.commit_approve(_schedule=schedule,created_by=request.user)
                return HttpResponseRedirect("/approved/done")
            else:
                form.save_form(_schedule=schedule,created_by=request.user)
                return HttpResponseRedirect("/approved/unapprove")
    else:
        form = ApproveForm(instance=approve)
    c = RequestContext(request)
    c.update(csrf(request))
    c["form"]=form
    createExtInfo(request, c)
    return render_to_response("approved/do.html",c)